'This is test cases for Log.py '
import sys
import os
import logging
import unittest

sys.path.append(os.path.abspath('..'))
from service.Log import *
from service.PlusterLog import PlusterLog
from service.pconfig import PConfig
from smtplib import *
class MyLogger(PlusterLog):
    """ This class illustrates how to use PlusterLog to logging
    Read logging section in Manual to get more information about
    methods in self.log"""

    def __init__ (self):
        """ setup code"""
        PlusterLog.__init__(self)

    def speak_hello(self):
        """ Use info method to speak """
        self.log.info('Hello, Leo')

    def speak_error (self):
        """ Send out error message"""
        self.log.error('An error occurred.')

    def speak_critical (self):
        """ Create a critical to send out mail"""
        self.log.critical("Test Critical Notification")

class TestLog (unittest.TestCase):
    """ Test Case for Log.py and PlusterLog.py"""
    def setUp(self):
        """Create LogDoc then we can receive message"""
        cfg="""
[cluster]
mail = hide1713@sina.com
name = ziqiang3000
passwd = yukikaze1985
send_to = hide1713@gmail.com
smtp = smtp.sina.com
total_node = 206

[debug]
debuglevel = 0

[logger]
file_name = ./log/msg.log
file_on = true
file_size_limit = 2000
mail_on = false
view_limit = 1000

[main_server]
address = 127.0.0.1
net = lo
port = 8888

[node]
net = lo
port = 7999

[rrd]
rrd_path = ./rrd/

[user]
root = No Description
ziqiang3000 = Cluster

[xmlrpc]
port_start = 8888
reuse = true
task_poolsize = 10

"""
        if not os.path.exists('pluster.cfg'):
            open('pluster.cfg','w').write(cfg)
        if not os.path.exists('log/msg.log'):
            try:
                os.mkdir('log')
            except:
                pass
            l=open('log/msg.log','w')
            l.write(' ')
            l.close()

        result=PConfig()
        result.logger_file_on=True
        result.logger_file_size_limit=20
        result.logger_mail_on=True
        result.cluster_mail='hide1713@sina.com'
        result.cluster_passwd='yukikaze1985'
        result.cluster_smtp='smtp.sina.com'
        logging.basicConfig()
        logging.getLogger().setLevel(logging.INFO)
        self.log_doc = LogDoc()
        self.speaker = MyLogger()
        self.log_doc.StartViewLog()

    def tearDown (self):
        """ Remove log file """
        try:
            os.remove('log/msg.log')
            os.rmdir('log')
        except:
            pass



    def test_get_new_log (self):
        """ Test GetNewLog() """
        self.speaker.speak_hello() #put 'Hello, Leo' in queue
        self.assertEqual('Hello, Leo\n', \
                             self.log_doc.GetNewLog(fmt='%(message)s'))
        self.speaker.speak_error()
        self.assertEqual('An error occurred.\n',
                             self.log_doc.GetNewLog(fmt='%(message)s'))

    def test_file_log (self):
        """ Test File Log"""
        self.speaker.speak_error()
        self.log_doc.StopFileLog()
        filep = open('log/msg.log')
        result = filep.readline()
        for i in range(20):
            self.speaker.speak_error()
        self.assertTrue(result.endswith('An error occurred.\n'))
        self.log_doc.RemoveLogFile('log/msg.log')
        self.assertRaises(OSError, self.log_doc.RemoveLogFile, \
                             './')
        self.assertRaises(OSError, self.log_doc.RemoveLogFile, \
                              'not_exists.file')
        filep.close()

    def test_email_log (self):
        """ Test email handler"""
        print 'self.log.critical() will send out a mail to everyone ' \
            + 'in send_to option in pluster.cfg'
        try:
            self.speaker.speak_critical()
        except SMTPAuthenticationError:
            print """

Can not login send mail account.This happend when using gmail as smtp server

Please read pluster.cfg in cluster section
mail = pluster.mail@gmail.com
passwd = pluster.

go to mail.google.com and login that account will fix this problem
"""

        self.log_doc.StopMailLog()


if __name__ == '__main__':
    unittest.main()
